{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9122b86d-c141-40d4-adcc-41ab562da76f",
   "metadata": {},
   "source": [
    "Chapter 07\n",
    "# 利用两层列表生成式计算矩阵逐项积\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "16c35862-1ce1-4aac-a061-3b7746dd7325",
   "metadata": {},
   "outputs": [],
   "source": [
    "def hadamard_prod(M1, M2):\n",
    "    if (len(M1) != len(M2) or \n",
    "        len(M1[0]) != len(M2[0])):\n",
    "        raise ValueError(\"Matrices must have the same shape\")\n",
    "\n",
    "    result = [[M1[i][j] * M2[i][j] \n",
    "               for j in range(len(M1[0]))] \n",
    "              for i in range(len(M1))]\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c2cda6be-27bf-4413-a378-04f49fabd411",
   "metadata": {},
   "outputs": [],
   "source": [
    "A = [[1, 2],\n",
    "     [3, 4]]\n",
    "B = [[2, 3],\n",
    "     [4, 5]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e4848fab-dfc9-4384-bf99-1c408ccc4852",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算矩阵逐项积\n",
    "C = hadamard_prod(A, B)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
